import re
import sys
from pywinauto import Application, Desktop, mouse, keyboard
import time

from utils.get_print import GetPrint


class Sudoku:
    level = {
        0: "小学生",
        1: "中学生",
        2: "大学生",
        3: "博士后",
    }

    def __init__(self) -> None:
        self.app = Application(backend="uia")
        self.des = Desktop(backend="uia")

    def start(self) -> None:
        try:
            self.app = self.app.connect(title_re="数独", timeout=10)
        except:
            keyboard.send_keys("{LWIN}")
            time.sleep(0.3)
            self.des["启动"].child_window(
                title="所有应用", control_type="TabItem"
            ).click_input()
            time.sleep(0.5)
            self.des["启动"].child_window(title="A", control_type="Group").click_input()
            time.sleep(0.5)
            self.des["启动"].child_window(
                title="S", control_type="ListItem"
            ).click_input()
            time.sleep(0.5)
            self.des["启动"].child_window(
                title="数独(sudoku)",
                control_type="ListItem",
            ).click_input()
            time.sleep(0.5)
            self.app = self.app.connect(title_re="数独", timeout=10)

        self.sudoku = self.app["数独(sudoku)"]
        self.sudoku.restore()


    def select_level(self, level=0, sub_level=1) -> None:
        try:
            self.sudoku.child_window(auto_id="time", control_type="Text").texts()
        except:
            self.sudoku.child_window(
                title=self.level[level], control_type="Button"
            ).click_input()
            self.sudoku.child_window(
                title=str(sub_level), control_type="Button"
            ).click_input()

    def ans_ele(self):
        stdout = sys.stdout
        sys.stdout = GetPrint()
        self.sudoku.dump_tree()
        self.dump_tree = sys.stdout.buff
        sys.stdout = stdout

        m = re.findall(r'child_window\(.*(\d).*auto_id="(\d+)", control_type="Button"\)', self.dump_tree)

        print(m)

if __name__ == "__main__":
    s = Sudoku()
    s.start()
    s.select_level(1, 1)
    s.ans_ele()
